<template>
	<view class="">
		<view class="header header_wi" :style="'padding-top: ' + navH + 'px;'">
		    <view class="header_height" :style="'height:' + gaodu + 'px;line-height:' + gaodu + 'px;top:' + gaodutops + 'px;'">
		        <view class="index_h_cont3">
		            <view class="index_wenben_img" @tap="jumpzuo">
		                <image src="http://daigou.sllowly.cn/assets/api/images/dzx_img33.png" mode="widthFix"></image>
		            </view>
		            <view class="index_wenben">{{$t('gouwuches.title')}}</view>
		        </view>
		    </view>
		    <view class="coloe_title">s</view>
		</view>
		<view class="index_center" :style="'padding-top:' + (navH + 50) + 'px;'">
			<view class="containers p-bottom">
			    <view class="flow-list">
			        <view v-if="goods_list.length">
			            <view class="cart-edit-wrap dis-flex flex-x-end">
			                <text v-if="action === 'complete'" @tap.stop.prevent="switchAction" class="f-30" data-action="edit">{{$t('gouwuches.bianji')}}</text>
			                <text v-if="action === 'edit'" @tap.stop.prevent="switchAction" class="f-30" data-action="complete">{{$t('gouwuches.wancheng')}}</text>
			            </view>
			            <view v-for="(item, index) in goods_list" :key="index">
			                <view class="dish-item dis-flex flex-y-center" :data-index="index" :style="item.txtStyle">
			                    <!-- 选择框 -->
			                    <view class="dish-item-radio" @tap.stop.prevent="onChecked" :data-index="index">
			                        <label class="radio">
			                            <radio :checked="item.checked" color="#ff495e"></radio>
			                        </label>
			                    </view>
			                    <view class="dish-item-wrp dis-flex flex-box">
			                        <!-- 商品图片 -->
			                        <navigator hover-class="none" :url="'../goods/index?goods_id=' + item.goods_id">
			                            <view class="dish-item-pic">
			                                <image mode="aspectFill" class="image" :src="item.goods_image"></image>
			                            </view>
			                        </navigator>
			                        <!-- 商品信息 -->
			                        <view class="dish-item-info flex-box">
			                            <navigator hover-class="none" :url="'../goods/index?goods_id=' + item.goods_id">
			                                <view class="goods-name">
			                                    <text class="twolist-hidden f-28 col-3">{{ item.goods_name }}</text>
			                                </view>
			                                <view class="goods-attr dis-flex">
			                                    <text class="col-7 f-24">{{ item.goods_sku.goods_attr }}</text>
			                                </view>
			                            </navigator>
			                            <view class="dis-flex flex-x-between m-top20">
			                                <!-- 商品价格 -->
			                                <view class="wx-goods_price dis-flex flex-y-center">
			                                    <text v-if="item.is_user_grade" class="dish-item-money">￥{{ item.grade_goods_price }}</text>
			                                    <text v-else class="dish-item-money">￥{{ item.goods_price }}</text>
			                                </view>
			                                <!-- 数量选择器 -->
			                                <view class="select-number">
			                                    <button
			                                        @tap.stop.prevent="onSubCount"
			                                        :class="'default ' + (item.total_num > 1 ? '' : 'disabled')"
			                                        :data-index="index"
			                                        :data-sku-id="item.goods_sku_id"
			                                        type="default"
			                                    >
			                                        -
			                                    </button>
			                                    <input @input="importTo" :disabled="true" type="number" :value="item.total_num" />
			                                    <button @tap.stop.prevent="onAddCount" class="default" :data-index="index" :data-sku-id="item.goods_sku_id" type="default">+</button>
			                                </view>
			                            </view>
			                            <!-- 删除按钮 -->
			                            <!-- <view catchtap="del" class="flow-dete" data-goods-id="{{item.goods_id}}" data-sku-id="{{item.goods_sku_id}}">
			            <text class="iconfont icon-lajixiang"></text>
			          </view> -->
			                        </view>
			                    </view>
			                </view>
			            </view>
			            <!-- 底部操作栏 -->
			            <view class="cart-tab-wrp">
			                <view class="cart-item-total cart-tab-item dis-flex flex-y-center">
			                    <view class="checked-all">
			                        <label @tap.stop.prevent="onCheckedAll" class="radio dis-flex flex-y-center">
			                            <radio class="margin-right: 10rpx;" :checked="checkedAll" color="#ff495e"></radio>
			                            <text class="f-28">{{$t('gouwuches.quanxuan')}}</text>
			                        </label>
			                    </view>
			                    <view v-if="action === 'complete'" class="cart-item-total-price dis-flex">
			                        <text class="f-28 col-m">{{$t('gouwuches.heji')}}：￥{{ cartTotalPrice }}</text>
			                    </view>
			                </view>
			                <view class="cart-tab-item_1">
			                    <view v-if="action === 'complete'" @tap.stop.prevent="submit" class="cart-tab-item-btn">{{$t('gouwuches.qujiesuan')}}</view>
			                    <view v-if="action === 'edit'" @tap.stop.prevent="onDelete" class="cart-tab-item-btn">{{$t('gouwuches.shanchu')}}</view>
			                </view>
			            </view>
			        </view>
			        <view v-else>
			            <view class="yoshop-notcont">
			                <text class="iconfont icon-wushuju"></text>
			                <text class="cont">{{$t('gouwuches.qin')}}</text>
			                <view @tap.stop.prevent="goShopping" class="flow-btn-min">{{$t('gouwuches.qugouwu')}}</view>
			            </view>
			        </view>
			    </view>
			</view>
			
		</view>
	</view>
    
</template>

<script>
const app = getApp(); // 工具类

import Util from '../../utils/util.js';
let request = require('../../utils/require');
export default {
    data() {
        return {
			navH: 0,
			gaodu: app.globalData.height,
			gaodutops: app.globalData.top,
            isLogin: false,

            // 商品列表
            goods_list: [],

            // 当前动作
            action: 'complete',

            // 选择的商品
            checkedData: [],

            // 是否全选
            checkedAll: false,

            // 商品总价格
            cartTotalPrice: '0.00',

            order_total_price: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad(options) {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let _this = this;
        _this.isLogin = app.globalData.checkIsLogin()
		console.log(_this.isLogin,"?")
// 获取购物车列表
          _this.getCartList();   
		  _this.dizhilist();
        if (_this.isLogin) {
           
        }
    },
    methods: {
		dizhilist() {
		    var that = this;
		    var data = {
		        token: uni.getStorageSync('token')
		    };
		    request.post(`index.php?s=/api/address/lists&wxapp_id=` + uni.getStorageSync('web_id'), data).then((res) => {
		        if (res.data.code == 1) {
		            
		        }
		    });
		},
		jumpzuo() {
		    uni.navigateBack()
		},
        /**
         * 获取购物车列表
         */
        getCartList() {
            let _this = this;
			var data = {
				token: uni.getStorageSync('token')
			}
			request.post(`index.php?s=/api/cart/lists&wxapp_id=` + uni.getStorageSync('web_id'), data).then((res) => {
			    if (res.data.code == 1) {
					_this._initGoodsChecked(res.data.data);
			    } else {
			        uni.showToast({
			            title: res.data.msg,
			            icon: 'none'
			        });
			    }
			});
			
        },

        /**
         * 初始化商品选中状态
         */
        _initGoodsChecked(data) {
            let _this = this;

            let checkedData = _this.getCheckedData(); // 将商品设置选中

            data.goods_list.forEach((item) => {
                item.checked = Util.inArray(`${item.goods_id}_${item.goods_sku_id}`, checkedData);
            });
                _this.goods_list = data.goods_list;
                _this.order_total_price = data.order_total_price;
                _this.action = 'complete';
                _this.checkedAll = checkedData.length == data.goods_list.length;
          // 更新购物车已选商品总价格

            _this.updateTotalPrice();
        },

        /**
         * 选择框选中
         */
        onChecked(e) {
            let _this = this;

            let index = e.currentTarget.dataset.index;
            let goods = _this.goods_list[index];
            let checked = !goods.checked; // 选中状态
            _this.goods_list[index].checked = checked;
            _this.onUpdateChecked(); // 更新购物车已选商品总价格
            _this.updateTotalPrice(); // 更新全选状态
            _this.checkedAll = _this.getCheckedData().length == _this.goods_list.length
        },

        /**
         * 获取选中的商品
         */
        getCheckedData() {
            let checkedData = uni.getStorageSync('checkedData');
            return checkedData ? checkedData : [];
        },

        /**
         * 选择框全选
         */
        onCheckedAll(e) {
            let _this = this;

            let goodsList = _this.goods_list; // 更新商品选中记录
            goodsList.forEach((item) => {
                item.checked = !_this.checkedAll;
            });
            _this.goods_list = goodsList,
            _this.checkedAll = !_this.checkedAll
            // 更新购物车已选商品总价格
            _this.updateTotalPrice(); // 更新选中记录
            _this.onUpdateChecked();
        },

        /**
         * 更新商品选中记录
         */
        onUpdateChecked() {
            let _this = this;
            let checkedData = [];
            _this.goods_list.forEach((item) => {
                if (item.checked == true) {
                    checkedData.push(`${item.goods_id}_${item.goods_sku_id}`);
                }
            });
            uni.setStorageSync('checkedData', checkedData);
        },

        /**
         * 切换编辑/完成
         */
        switchAction(e) {
            let _this = this;
            _this.action = e.currentTarget.dataset.action
        },

        /**
         * 删除商品
         */
        onDelete() {
            let _this = this;
            let cartIds = _this.getCheckedIds();
            if (!cartIds.length) {
                app.globalData.showError(_this.$t('gouwuches.weishangpin'));
                return false;
            }
            uni.showModal({
                title: _this.$t('gouwuches.tishi'),
                content: _this.$t('gouwuches.weiyichu'),
                success(e) {
                    if (e.confirm) {
						var data = {
							  goods_sku_id: cartIds,
							  token: uni.getStorageSync('token')
						}
						request.post(`index.php?s=/api/cart/delete&wxapp_id=` + uni.getStorageSync('web_id'), data).then((res) => {
						    if (res.data.code == 1) {
								_this.onDeleteEvent(cartIds);
								 _this.getCartList();
						    } else {
						        uni.showToast({
						            title: res.data.msg,
						            icon: 'none'
						        });
						    }
						});
                    }
                }
            });
        },

        /**
         * 商品删除事件
         */
        onDeleteEvent(cartIds) {
            let _this = this;
            cartIds.forEach((cartIndex) => {
                _this.goods_list.forEach((item, goodsIndex) => {
                    if (cartIndex == `${item.goods_id}_${item.goods_sku_id}`) {
                        _this.goods_list.splice(goodsIndex, 1);
                    }
                });
            }); // 更新选中记录

            _this.onUpdateChecked();

            return true;
        },

        /**
         * 获取已选中的商品
         */
        getCheckedIds() {
            let _this = this;

            let arrIds = [];

            _this.goods_list.forEach((item) => {
                if (item.checked === true) {
                    arrIds.push(`${item.goods_id}_${item.goods_sku_id}`);
                }
            });

            return arrIds;
        },

        /**
         * 更新购物车已选商品总价格
         */
        updateTotalPrice() {
            let _this = this;

            let cartTotalPrice = 0;

            _this.goods_list.forEach((item) => {
                if (item.checked === true) {
                    cartTotalPrice = _this.mathadd(cartTotalPrice, item.total_price);
                }
            });

            _this.cartTotalPrice = Number(cartTotalPrice).toFixed(2)
        },

        /**
         * 递增指定的商品数量
         */
        onAddCount(e) {
            let _this = this;
            let index = e.currentTarget.dataset.index;
            let goodsSkuId = e.currentTarget.dataset.skuId;
            let goods = _this.goods_list[index]; // order_total_price = _this.data.order_total_price;
            // 后端同步更新

            uni.showLoading({
                title: _this.$t('m.jiazai'),
                mask: true
            });
			var data = {
				 goods_id: goods.goods_id,
				 goods_num: 1,
				 goods_sku_id: goodsSkuId,
				 token: uni.getStorageSync('token')
			}
			request.post(`index.php?s=/api/cart/add&wxapp_id=` + uni.getStorageSync('web_id'), data).then((res) => {
			    if (res.data.code == 1) {	
					_this.getCartList();
			    } else {
			        uni.showToast({
			            title: res.data.msg,
			            icon: 'none'
			        });
			    }
			});
			
        },

        /**
         * 递减指定的商品数量
         */
        onSubCount(e) {
            let _this = this;

            let index = e.currentTarget.dataset.index;
            let goodsSkuId = e.currentTarget.dataset.skuId;
            let goods = _this.goods_list[index];
            if (goods.total_num > 1) {
                // 后端同步更新
                uni.showLoading({
                    title: _this.$t('m.jiazai'),
                    mask: true
                });
				var data = {
					token: uni.getStorageSync('token'),
					goods_id : goods.goods_id,
					goods_sku_id : goodsSkuId
				}
				request.post(`index.php?s=/api/cart/sub&wxapp_id=` + uni.getStorageSync('web_id'), data).then((res) => {
				    if (res.data.code == 1) {
						uni.showToast({
						    title: res.data.msg,
						    icon: 'none'
						});
						
						_this.getCartList();
				    } else {
				        uni.showToast({
				            title: res.data.msg,
				            icon: 'none'
				        });
				    }
				});
            }
        },

        /**
         * 购物车结算
         */
        submit() {
            let _this = this;

            let cartIds = _this.getCheckedIds();

            if (!cartIds.length) {
                app.globalData.showError(_this.$t('gouwuches.weishangpin'));
                return false;
            }

            uni.navigateTo({
                url: '../flow/checkout?order_type=cart&cart_ids=' + cartIds
            });
        },

        /**
         * 加法
         */
        mathadd(arg1, arg2) {
            return (Number(arg1) + Number(arg2)).toFixed(2);
        },

        /**
         * 减法
         */
        mathsub(arg1, arg2) {
            return (Number(arg1) - Number(arg2)).toFixed(2);
        },

        /**
         * 去购物
         */
        goShopping() {
           uni.navigateTo({
           	url: '/pages/home/index'
           });
        },

        importFun() {
            console.log('占位：函数 import 未声明');
        }
    }
};
</script>
<style>
@import './index.css';
</style>
